import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam_result.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/bean/bean_train_exam_appro.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/mine/mine_address_mine_depart_page.dart';
import 'package:flutter_learn_vi/src/page/mine/mine_select_enum.dart';
import 'package:flutter_learn_vi/src/page/train/train_exam_appro_page.dart';
import 'package:flutter_learn_vi/src/page/train/train_exam_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/16.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///培训详情页面二
class TrainTabDetails2StudentPage extends StatefulWidget {
  //培训ID
  final TrainApproveBean approveBean;

  //培训详情
  final TrainBean trainBean;

  const TrainTabDetails2StudentPage({Key key, this.approveBean, this.trainBean})
      : super(key: key);

  @override
  _TrainTabDetails2StudentPageState createState() =>
      _TrainTabDetails2StudentPageState();
}

class _TrainTabDetails2StudentPageState
    extends State<TrainTabDetails2StudentPage>
    with AutomaticKeepAliveClientMixin, TrainModel {
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    getUserSelectTrain();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "培训考试",
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // TrainStudentSelectCoursePage(
            //   approveBean: widget.approveBean,
            //   isScaffold: false,
            // ),
            buildElevatedButton(),
            Container(
              padding: EdgeInsets.all(16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("小提示:"),
                  SizedBox(
                    width: 14,
                  ),
                  Expanded(
                    child: Text(
                      "培训课程参与完成后，班主任或者平台管理员会开启考试通道，点击参与考试来获取本次培训的合格证书",
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget buildElevatedButton() {
    if (_userSelectTrainBena == null) {
      return Container();
    }

    //5 进行中 ；6已完成
    //_userSelectTrainBena.trainStatus
    int trainStatus = 6;
    if (trainStatus == 6) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(left: 12, right: 12, top: 12),
            child: Card(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "已完成培训",
                      style: TextStyle(
                          fontWeight: FontWeight.w500, color: Colors.black),
                    ),
                    SizedBox(height: 4),
                    Text("完成时间 ${_userSelectTrainBena.endTime ?? "--"}"),
                  ],
                ),
              ),
            ),
          ),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(left: 12, right: 12),
            child: Card(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "${_examResultList == null ? '' : "有效考试结果"}",
                      style: TextStyle(
                          fontWeight: FontWeight.w500, color: Colors.black),
                    ),
                    SizedBox(height: 4),
                    Text(
                      "*请注意：多次考试时，提交培训审核时，会默认选择最高成绩为有效成绩",
                      style: TextStyle(fontSize: 12, color: Colors.red),
                    ),
                    maxExamResult == null
                        ? SizedBox()
                        : Container(
                            margin: EdgeInsets.only(top: 8),
                            padding: EdgeInsets.all(6),
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: Colors.grey[200],
                                borderRadius:
                                    BorderRadius.all(Radius.circular(4))),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        "考试时间 ${maxExamResult.createTime}",
                                        style: TextStyle(
                                            fontWeight: FontWeight.normal,
                                            fontSize: 14),
                                      ),
                                    ),
                                  ],
                                ),
                                Container(
                                  child: Row(
                                    children: [
                                      Text(
                                        "得分 ${maxExamResult.obtainScore / 10} 分",
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontWeight: FontWeight.normal,
                                            fontSize: 14),
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                    TextButton(
                      onPressed: () async {
                        int examId = widget.approveBean.examId;
                        if (examId == null || examId == 0) {
                          ToastUtils.showToast("请等待管理员创建考试后参与");
                          return;
                        }
                        await Get.to(
                          () => TrainExamPage(
                              approveBean: widget.approveBean,
                              examResultList: _examResultList),
                        );
                        _getTrainExamDetails();
                      },
                      child:
                          Text(_examResultList == null ? "参加考试" : "查看更多考试结果"),
                    )
                  ],
                ),
              ),
            ),
          ),
          showTrainApproveWidet(),
        ],
      );
    }

    return ElevatedButton(
      onPressed: () {
        studentFinishTrain();
      },
      child: Text("点击完成培训"),
    );
  }

  Widget showTrainApproveWidet() {
    if (widget.trainBean == null) {
      return SizedBox();
    }
    int showExamApprove = widget.trainBean.showExamApprove;
    if (showExamApprove == 0) {
      return SizedBox();
    }
    String approTime = "暂无";
    String approRemark = "暂无";

    Color textColor = Colors.grey;
    String approResult = "暂无";
    if (_beanTrainExamAppro != null) {
      //审批状态 0待审批  1通过 2拒绝 3 证书下发 4删除
      int statues = _beanTrainExamAppro.approStatues;
      if (statues == 1 || statues == 2 || statues == 3) {
        approTime = _beanTrainExamAppro.approTime;
        approRemark = _beanTrainExamAppro.approRemark;
        textColor = Colors.black;
      }
      if (statues == 0) {
        approResult = "待审批";
      } else if (statues == 1 || statues == 3) {
        approResult = "合格";
      } else if (statues == 2) {
        approResult = "不合格";
      } else {
        approResult = "--";
      }
    }
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(left: 12, right: 12),
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                "${_beanTrainExamAppro == null ? '' : "合格审批"}",
                style:
                    TextStyle(fontWeight: FontWeight.w500, color: Colors.black),
              ),
              SizedBox(height: 4),
              Text(
                "*请注意：请先参与考试，然后获取最佳成绩后，再提交合格审批，合格审批时需要选择审批人",
                style: TextStyle(fontSize: 12, color: Colors.red),
              ),
              _beanTrainExamAppro == null
                  ? SizedBox()
                  : Container(
                      margin: EdgeInsets.only(top: 8),
                      padding: EdgeInsets.all(6),
                      decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.all(Radius.circular(4))),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("提交时间：${_beanTrainExamAppro.createTime}"),
                          Text(
                            "审批结果：$approResult",
                            style: TextStyle(color: textColor),
                          ),
                          Text(
                            "审批时间：$approTime",
                            style: TextStyle(color: textColor),
                          ),
                        ],
                      ),
                    ),
              TextButton(
                onPressed: () {
                  if (_examResultList == null) {
                    ToastUtils.showToast("请先参与考试");
                    return;
                  }
                  if (_beanTrainExamAppro == null) {
                    studentTrainExam();
                  } else {
                    NavigatorUtils.pushPage(
                        context,
                        TrainExamApproPage(
                          beanTrainExamAppro: _beanTrainExamAppro,
                        ), callback: (value) {
                      _getTrainAppro();
                    });
                  }
                },
                child:
                    Text(_beanTrainExamAppro == null ? "提交合格审核" : "查看合格审核进度"),
              )
            ],
          ),
        ),
      ),
    );
  }

  //学生点击完成培训
  void studentFinishTrain() {
    showCommonAlertDialog(
        context: context,
        contentMessag: "确定完成培训???",
        selectText: "确定",
        cancleText: "取消操作",
        selectCallBack: () async {
          await userFinishTrain(flag: 2, trainId: widget.approveBean.trainId);
          getUserSelectTrain();
        });
  }

  void studentTrainExam() {
    showCommonAlertDialog(
        context: context,
        headerTitle: "确定提交审核吗???",
        contentMessag: "提交审核 需要选择审批人，审批人审批通过后，可获取合格证书，也会记录在档案系统中",
        selectText: "提交审核",
        cancleText: "取消操作",
        selectCallBack: () async {
          openApprolyFunction();
        });
  }

  void openApprolyFunction() {
    NavigatorUtils.pushPage(
      context,
      MineSelectDepartmentPage(
        mineBean: UserHelper.getInstance.mineBean,
        mineSelectType: MineSelectType.train,
      ),
      callback: (value) {
        if (value != null) {
          UserBean userBean = value;
          commitTrainExam(userBean);
        } else {
          ToastUtils.showToast("已取消选择");
        }
      },
    );
  }

  void commitTrainExam(UserBean userBean) {
    showCommonAlertDialog(
        context: context,
        headerTitle: "确定提交审核吗???",
        contentMessag: "已选择审批人 【 ${userBean.userPost} - ${userBean.reamName} 】",
        selectText: "提交审核",
        cancleText: "取消操作",
        selectCallBack: () async {
          _commitTrainAppro(userBean);
        });
  }

  TrainBean _userSelectTrainBena;

  //考试结果
  List<BeanExamResult> _examResultList;

  //最高
  BeanExamResult maxExamResult;

  //审批情况
  BeanTrainExamAppro _beanTrainExamAppro;
  bool _isLoading = true;

  //查询用户参与培训 的详情
  void getUserSelectTrain() async {
    _userSelectTrainBena = await querySelectTrain(widget.approveBean.trainId);
    await _getTrainExamDetails();
    await _getTrainAppro();
  }

  //提交培训审核
  void _commitTrainAppro(UserBean userBean) async {
    BeanExamResult beanExamResult;
    for (int i = 0; i < _examResultList.length; i++) {
      if (beanExamResult == null) {
        beanExamResult = _examResultList[i];
      } else {
        BeanExamResult item = _examResultList[i];
        if (item.obtainScore > beanExamResult.obtainScore) {
          beanExamResult = item;
        }
      }
    }

    await commitTrainAppro(widget.approveBean.trainId,
        widget.approveBean.examId, beanExamResult, userBean);
    await _getTrainAppro();
  }

  //获取培训考试审核详情
  Future<bool> _getTrainAppro() async {
    _beanTrainExamAppro =
        await getTrainExamApproDetails(widget.approveBean.trainId);
    if (mounted) {
      setState(() {});
    }
    return true;
  }

  //查询考试详情
  Future<bool> _getTrainExamDetails() async {
    LogUtils.e("开始获取考试详情");
    _examResultList = await getTrainExamDetails(
        widget.approveBean.examId, widget.approveBean.trainId);
    if (_examResultList != null) {
      LogUtils.e("考试详情获取结束 ${_examResultList.length}");

      for (int i = 0; i < _examResultList.length; i++) {
        if (maxExamResult == null) {
          maxExamResult = _examResultList[i];
        } else {
          BeanExamResult item = _examResultList[i];
          if (item.obtainScore > maxExamResult.obtainScore) {
            maxExamResult = item;
          }
        }
      }
    } else {
      LogUtils.e("f考试详情获取结束 list is null ");
    }

    _isLoading = false;
    if (mounted) {
      setState(() {});
    }
    return true;
  }
}
